import React, {useState} from "react";
import {Button, Icon, Tabs} from "antd";
import PropTypes from "prop-types";

const {TabPane} = Tabs;

const TabList = ({files, activeId, unSaveIds, onTabClick, onCloseTab}) => {
    const [ activeKey, setActiveKey ] = useState(files[0].id);

    const remove = targetKey => {
        let lastIndex = false;
        files.forEach((file, i) => {
            if (file.id === targetKey) {
                lastIndex = i - 1;
            }
        });
        const filesFilter = files.filter(file => file.id !== targetKey);
        if (filesFilter.length && activeKey === targetKey) {
            if (lastIndex >= 0) {
                setActiveKey(files[lastIndex].key);
            } else {
                setActiveKey(files[0].key);
            }
        }
        files = filesFilter;
    };

    return (
        <Tabs
            hideAdd
            onChange={(key) => {
                setActiveKey(key);
                onTabClick(key);
            }}
            activeKey={activeKey}
            type="editable-card"
            onEdit={(key) => remove(key)}
        >
            {
                files.map(file => {
                    return (
                        <TabPane tab={file.title} key={file.id} >
                            {file.body}
                        </TabPane>
                    )
                })
            }
        </Tabs>
    )
};

// 属性检查
TabList.prototype = {
    files: PropTypes.array,
    activeId: PropTypes.string,
    unSaveIds: PropTypes.array,
    onTabClick: PropTypes.func,
    onCloseTab: PropTypes.func
};

// 属性默认值
TabList.defaultProps = {
    files: [
        {
            id: '1',
            title: 'first post',
            body: 'should be aware of this',
            createdAt: 1563762965704
        },
        {
            id: '2',
            title: 'second post',
            body: '## this is the title',
            createdAt: 1563762965704
        }
    ],
    unSaveIds: []
};

export default TabList;
